package com.zhonghan.recharge.service.impl;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.bean.ZhCardOrder;
import com.zhonghan.common.enums.ResultStatus;
import com.zhonghan.common.utils.StringUtils;
import com.zhonghan.recharge.dao.BmItemDao;
import com.zhonghan.recharge.dao.ZhCardReceiveDao;
import com.zhonghan.recharge.dao.ZhFillCardDao;
import com.zhonghan.recharge.dao.ZhGascardOrderDao;
import com.zhonghan.recharge.pojo.ZhCardReceive;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.service.JiSuRechargeService;
import com.zhonghan.recharge.service.ZhCardReceiveService;
import com.zhonghan.recharge.service.ZhGascardOrderService;
@Service
public class ZhGascardOrderServiceImpl implements ZhGascardOrderService{
	private static final Logger logger = LogManager.getLogger(ZhGascardOrderServiceImpl.class);

	@Autowired
    private ZhGascardOrderDao zhGascardOrderDao;
    
    @Autowired
    private BmItemDao bmItemDao;
    
    @Autowired
    private JiSuRechargeService jiSuRechargeService;
    
    @Autowired
    private ZhCardReceiveDao zhCardReceiveDao;
    
    @Autowired
    private ZhCardReceiveService zhCardReceiveService;
    /*public ZhGascardOrder saveOrder(String gasNumber, String gasName, String gasPhone, String gasType, String reCardNo,
			Integer facePrice){
    	
    	try{
    		// 空的？
    		BmItem bmItem = new BmItem();
			bmItem.setFacePrice(Double.valueOf(facePrice));
			bmItem.setOperatorType(gasType);
			bmItem = bmItemDao.selectBmItemByObj(bmItem);
    		
    		ZhGascardOrder order = new ZhGascardOrder();
        	order.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        	order.setFillCardSequence(reCardNo);
        	// 斑马商品id
    		order.setBmItemId(bmItem.getBmItemId());
    		// 斑马商品名称
    		order.setBmItemName(bmItem.getItemName());
    		// 斑马商品的数量
    		order.setBmItemNum(1);
    		// 充值人姓名
    		order.setFillName(gasName);
    		// 电话
    		order.setTelephone(gasPhone);
    		// 充值油卡编号
    		order.setGascardNo(gasNumber);
    		// 生成订单的时间
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		String time = sdf.format(new Date());
    		order.setOrderTime(time);
    		//openid ???
    		order.setOpenid("");
    		// 面额
        	order.setFacePrice(bmItem.getFacePrice());
        	// 订单充值金额
        	order.setRechargeAmount(bmItem.getFacePrice());
        	// 状态
        	order.setRechargeState("0");
        	
    		// 加入到数据库Order表
        	insertZhGascardOrder(order);
        	return order;
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return null;
    }*/
    @Override
    public long getZhGascardOrderRowCount(){
        return zhGascardOrderDao.getZhGascardOrderRowCount();
    }
    @Override
    public List<ZhGascardOrder> selectZhGascardOrder(){
        return zhGascardOrderDao.selectZhGascardOrder();
    }
    @Override
    public List<ZhGascardOrder> selectZhGascardOrderByObj(ZhGascardOrder obj){
        return zhGascardOrderDao.selectZhGascardOrderByObj(obj);
    }
    @Override
    public ZhGascardOrder selectZhGascardOrderById(Integer id){
        return zhGascardOrderDao.selectZhGascardOrderById(id);
    }
    @Override
    public int insertZhGascardOrder(ZhGascardOrder value){
        return zhGascardOrderDao.insertZhGascardOrder(value);
    }
    @Override
    public int insertNonEmptyZhGascardOrder(ZhGascardOrder value){
        return zhGascardOrderDao.insertNonEmptyZhGascardOrder(value);
    }
    @Override
    public int insertZhGascardOrderByBatch(List<ZhGascardOrder> value){
        return zhGascardOrderDao.insertZhGascardOrderByBatch(value);
    }
    @Override
    public int deleteZhGascardOrderById(Integer id){
        return zhGascardOrderDao.deleteZhGascardOrderById(id);
    }
    @Override
    public int updateZhGascardOrderById(ZhGascardOrder enti){
        return zhGascardOrderDao.updateZhGascardOrderById(enti);
    }
    @Override
    public int updateNonEmptyZhGascardOrderById(ZhGascardOrder enti){
        return zhGascardOrderDao.updateNonEmptyZhGascardOrderById(enti);
    }

    public ZhGascardOrderDao getZhGascardOrderDao() {
        return this.zhGascardOrderDao;
    }

    public void setZhGascardOrderDao(ZhGascardOrderDao zhGascardOrderDao) {
        this.zhGascardOrderDao = zhGascardOrderDao;
    }

    
    /**
     * 查询订单
     */
    public Result selectZhGascardOrderByCondition(String orderNo,String gascardNo,String telephone,String fillCardSequence,
    		String rechargeState,String beginTime,String endTime,String orderType, Integer pageNum,Integer pageSize){
    	
    	pageNum = pageNum == null ? 0 : pageNum;
    	pageSize = pageSize == null ? 0 : pageSize;
    	
		ZhGascardOrder order = new ZhGascardOrder();
		if(StringUtils.isNotEmpty(orderNo)){
			order.setOrderNo(orderNo);
		}
		if(StringUtils.isNotEmpty(gascardNo)){
			order.setGascardNo(gascardNo);
		}
		if(StringUtils.isNotEmpty(telephone)){
			order.setTelephone(telephone);
		}
		if(StringUtils.isNotEmpty(fillCardSequence)){
			order.setFillCardSequence(fillCardSequence);
		}
		if(StringUtils.isNotEmpty(rechargeState)){
			order.setRechargeState(rechargeState);
		}
		if(StringUtils.isNotEmpty(beginTime)){
			order.setBeginTime(beginTime);
		}
		if(StringUtils.isNotEmpty(endTime)){
			order.setEndTime(endTime);
		}
		if(StringUtils.isNotEmpty(orderType)){
			order.setOrderType(orderType);
		}
		order.setOrderBy("orderTime");
		order.setSortBy("desc");
		
		Result result = new Result();
		try {
			
			PageHelper.startPage(pageNum, pageSize);
			List<ZhGascardOrder> orderList = zhGascardOrderDao.selectZhGascardOrderByCondition(order);
			PageInfo<ZhGascardOrder> pageInfo = new PageInfo<>(orderList);
			result.setCode(ResultStatus.SUCCESS.getCode());
			result.setData(pageInfo);
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResultStatus.BUSYNESS.getCode());
			result.setMsg(ResultStatus.BUSYNESS.getDescription());
		}
    	
    	return result;
    }
    
    @Autowired
    private ZhFillCardDao fillCardDao;
    // 1.更新订单，2.还原充值卡
	@Override
	@Transactional
	public void updateRechargeStateByOrderNoByCallBack(String orderNo, String rechargeState,String operateTime) throws Exception{
		// TODO Auto-generated method stub
		try {
			//更改订单
			zhGascardOrderDao.updateRechargeStateByOrderNoByCallBack(orderNo,rechargeState,operateTime);
			ZhGascardOrder order = zhGascardOrderDao.selectZhGascardOrderByOrderNo(orderNo);
			logger.info("更新订单:还原充值卡:"+rechargeState+" "+order.getOrderNo()+" "+order.getFillCardSequence());
			//还原卡片  1 代表已发卡  2 代表已消费
			if(!"1".equals(rechargeState)) {
				int num = fillCardDao.updateStatusBySequence("1", order.getFillCardSequence());
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		}
		
		
	}
	/**
	 * api接口  查询订单信息
	 * @param orderNo
	 * @return
	 */
	public ZhCardOrder selectOrderToApiByOrderNo(String orderNo) {
		ZhGascardOrder order = zhGascardOrderDao.selectZhGascardOrderByOrderNo(orderNo);
		if(order != null) {
			ZhCardOrder cardOrder = new ZhCardOrder();
			cardOrder.setFacePrice(order.getFacePrice());
			cardOrder.setFillCardSequence(order.getFillCardSequence());
			cardOrder.setFillName(order.getFillName());
			cardOrder.setGascardNo(order.getGascardNo());
			cardOrder.setItemName(order.getBmItemName());
			cardOrder.setItemNum(order.getBmItemNum());
			cardOrder.setOperateTime(order.getOperateTime());
			cardOrder.setRechargeAmount(order.getRechargeAmount());
			cardOrder.setOrderNo(order.getOrderNo());
			cardOrder.setOrderTime(order.getOrderTime());
			cardOrder.setRechargeState(order.getRechargeState());
			cardOrder.setTelephone(order.getTelephone());
			return cardOrder;
		}else {
			return null;
		}
		
	}
	@Override
	public long getZhGascardOrderRowCountByObj(ZhGascardOrder obj) {
		
		return zhGascardOrderDao.getZhGascardOrderRowCountByObj(obj);
	}
	
	
	@Override
	public Result getOrderDetail(String orderNo) {
		Result result = new Result();
		
		try {
			ZhGascardOrder order = zhGascardOrderDao.selectZhGascardOrderByOrderNo(orderNo);
			
			if(order != null){
				
				if(!order.getRechargeState().equals("1")){
					if(order.getBmItemId().equals("jisu")){
						String bmBillId = order.getBmBillId();
						//ZhCardReceive zhCardReceive = zhCardReceiveDao.selectZhCardReceiveBySequence(order.getFillCardSequence());
						
						ZhCardReceive zhCardReceive = zhCardReceiveDao.selectZhCardReceiveBySequenceII(orderNo);
						
						if(zhCardReceive == null || zhCardReceive.getPortAppkey()== null || "".equals(zhCardReceive.getPortAppkey()) ) {
							zhCardReceive = new ZhCardReceive();
							zhCardReceive.setPortAppkey("2980c26878d61dc2");
							zhCardReceive.setPortAppsecret("5KW9IGrEak1QsP34q2tfGDXrWK9FpsQx");
							zhCardReceive.setPortUrl("http://api.jisuapi.com/fuelcardrecharge/recharge");
						}
						
						jiSuRechargeService.changeMyOrderRechargeStatusII(bmBillId, orderNo,zhCardReceive.getPortAppkey());
						logger.info("调用极速接口查询订单情况");
					}
					order = zhGascardOrderDao.selectZhGascardOrderByOrderNo(orderNo);
						
				}
				//拿到充值卡去查询
				String fillCardSequence = order.getFillCardSequence();
				ZhCardReceive receiver = zhCardReceiveService.selectZhCardReceiveBySequence(fillCardSequence);
				if(receiver != null){
					order.setReceiveName(receiver.getReceiveName());
				}
				
				result.setCode(ResultStatus.SUCCESS.getCode());
				result.setData(order);
			}else{
				result.setCode(ResultStatus.FAILURE.getCode());
				result.getMsg();
			}
			
		} catch (Exception e) {
			result.setCode(ResultStatus.BUSYNESS.getCode());
			result.setMsg(ResultStatus.BUSYNESS.getDescription());
			e.printStackTrace();
		}
		return result;
	}
	@Override
	public ZhGascardOrder selectZhGascardOrderByOrderNo(String orderNo) {
		
		return zhGascardOrderDao.selectZhGascardOrderByOrderNo(orderNo);
	}
  
}